<?php
use Think\Controller;

class BaseController extends Controller {
	public $user_id;

	public function _initialize() {

		$this->backUrl = $_SERVER['HTTP_REFERER'];
		$this->thisUrl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		//$this->backUrl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$this->pageName = CONTROLLER_NAME . "_" . ACTION_NAME;
		$this->HOST = $_SERVER['HTTP_HOST'];
		$this->empty = '<div class="empty">没有数据</div>';
		$this->set_user_id_by_uuid();
		$this->allow_origin();
		/*********登录信息******/
		$this->store_id = getStoreID();
		//	dump(session("user_id"));
		//session("user_id", '100107');
		$this->user_id = session("user_id");
		//	dump($this->user_id);
		if ($this->user_id) {
			$this->user_info = BoxModel("system_member")->load($this->user_id);
			$this->user_info_json = json_encode($this->user_info);
		}
		//推广者ID
		if ($InviteEarnPid = I('InviteEarnPid', "0", "intval")) {
			//session("InviteEarnPid",$InviteEarnPid);
			S(session_id(), $InviteEarnPid);
		}
		//dump( session("InviteEarnPid"));
		if (APP_DEBUG) {
			$this->jsController();
		}
		$this->is_mobile = mobile();
		$this->setAgent();

	}
	//用户使用的客户端
	function setAgent() {
		if (I('Agent', "0", "intval")) {
			$Agent = I('Agent');
		}

		if ($this->is_mobile) {
//移动
			$clientUtil = new \Common\Org\clientUtil(); //客户端操作系统
			$userAgent = $clientUtil->getPlatForm($_SERVER['HTTP_USER_AGENT']);
			if ($userAgent == 'Android') {
				$Agent = 4;
			} elseif ($userAgent == 'iOS') {
				$Agent = 3;
			} else {
				$Agent = 5;
			}

		}
//微信
		if (!checkAgent()) {
			$Agent = 2;
		}
		if (!$Agent) {
			$Agent = 1;
		}

		if ($this->user_id) {
			S('UserAgent_' . $this->user_id, $Agent, 600);
		}

	}

	protected function set_user_id_by_uuid() {
		$uuid = I('uuid');
		$key = I('runThreadKey');
		$runThreadKey = md5(C('runThreadKey'));
		//dump(I());
		//exit(json_encode($_POST));
		if ($uuid && $key == $runThreadKey) {
			$data = BoxModel("system_member_uuid")->where("uuid='$uuid'")->find();
			if ($data) {
				$user_id = $data['user_id'];
			} else {
				$user_id = BoxModel("system_member")->create_member_by_uuid($uuid);
			}
			session("user_id", $user_id);
		}
	}

	/*****是否充许跨域**/
	protected function allow_origin() {
		$key = I('runThreadKey');
		$runThreadKey = md5(C('runThreadKey'));
		header("Access-Control-Allow-Origin: *");
		if ($key == $runThreadKey) {
			header("Access-Control-Allow-Origin: *");
		} else {
			$domains = explode(".", $this->HOST);
			$top_domain = $domains[count($domains) - 2] . "." . $domains[count($domains) - 1];
			//		dump($top_domain);
			//				dump(DomainName);
			if ($top_domain == DomainName) {
				header("Access-Control-Allow-Origin: *");
			}
		}

	}

	/**********返回错误码******/
	protected function return_array($error, $msg) {
		$return['error'] = $error;
		if (is_array($msg)) {
			$return = array_merge($msg, $return);
		} else {
			$return['msg'] = $msg;
		}
		return $return;
	}

	protected function aReturn($flag = 1, $code = 0, $msg = '', $merge = null) {
		$return['flag'] = $flag;
		$return['code'] = $code;
		$return['msg'] = $msg;
		if (!empty($merge)) {
			$return = array_merge($merge, $return);
		}
		$this->ajaxReturn($return);
	}

	protected function jump($msg, $url) {
		header("Content-type: text/html; charset=utf-8");
		$new_url = $url ? $url : $_SERVER['HTTP_REFERER'];
		if (IS_AJAX) {
			if (strpos($url, "http") === false) {
				$new_url = "http://" . $_SERVER['HTTP_HOST'] . $new_url;
			}
			if (strpos($url, "?") === false) {
				$new_url .= "?IS_AJAX=1";
			} else {
				$new_url .= "&IS_AJAX=1";
			}
			$array = array(
				'msg' => $msg,
				'content' => '',
			);
			if ($url) {
				$array['content'] = $new_url;
			}
			echo "obj-" . json_encode($array);
		} else {
			if ($msg) {
				$msg = " alert('{$msg}');";
			}
			echo '<script language="javascript" type="text/javascript">' . $msg . ' window.location.href="' . $new_url . '"; </script>';
		}
		exit();
	}

	/***上传附$savePath='/slide/'$param=array(
		     * 'path'=>'slide',//文件保存目录，相对UploadPath
		     * 'maxSize'=>'',//文件大小限制
		     * 'exts'=>'',//后缀名
	*/
	public function _upload($p) {
//			$savePath=$p['path'];
		//$maxSize=$p['maxSize']?$p['maxSize']:"3145728";
		$p['rootPath'] = $p['rootPath'] ? $p['rootPath'] : UploadPath;
		$p['savePath'] = trim($p['savePath'], "/") . "/";
		//$exts=$p['exts']?$p['exts']:array('jpg', 'gif', 'png', 'jpeg');
		$config = C("UPLOAD_SITEIMG");
		if ($config['driverConfig']['type'] == "OSS") {
//上传一云服务器才有的上传设置
			$p['savePath'] = UploadPath . "/" . $p['savePath'];
		}
		$config['driverConfig'] = array_merge((array) $p, (array) $config['driverConfig']);
		$upload = new \Think\Upload($config); // 实例化上传类
		$upload->autoSub = true;
		$upload->rootPath = $p['rootPath'];
		$upload->savePath = $p['savePath'];
		$upload->subName = array('date', 'Ymd');
		$info = $upload->upload();
		if ($info) {
			return $info;
		} else {
			return $upload;
		}

	}

	/**
	 * 错误提示
	 */
	public function errormsg($url, $msg, $status = 0, $str = 'errormsg') {
		session($str, $msg);
		if ($status) {
			session('status', 1);
		}
		return $this->redirect($url);
	}

	/****display模板***/
	public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		$content = self::fetch($templateFile);
		echo $content;
	}

	/****display模板***/
	public function fetch($templateFile = "", $content = '', $prefix = '') {
		//dump($this->view->get());exit();
		if (I('from_wx_app') && trim($content) === "") {
			$data = $this->view->get();
			exit(json_encode($data));
		}
		if ($templateFile == "" && APP_URL_TYPE == 2) {
			$depr = C('TMPL_FILE_DEPR');
			$templateFile = CONTROLLER_NAME . $depr . ACTION_NAME;
			$templateFile = "./Apps/" . C('DEFAULT_MODULE') . "/View/" . $templateFile . C('TMPL_TEMPLATE_SUFFIX');
		} elseif (!is_file($templateFile) && APP_URL_TYPE == 2) {
			$templateFile = "./Apps/" . C('DEFAULT_MODULE') . "/View/" . BOX_MODULE_NAME . "/" . $templateFile . C('TMPL_TEMPLATE_SUFFIX');
		}
		return parent::fetch($templateFile, $content, $prefix);
	}

	/**********分页*********/
	public function setPager($count, $limit) {
		$Page = new Common\Org\Page($count, $limit); // 实例化分页类 传入总记录数和每页显示的记录数(12)
		$Page->setConfig('prev', '上一页');
		$Page->setConfig('next', '下一页');
		$Page->setConfig('first', '首页');
		$Page->setConfig('last', '末页');
		$Page->setConfig('theme', '%totalRow% %first% %upPage% %linkPage%  %downPage% %end%');
		$this->page = $Page->show(); // 分页显示输出
		$this->limit = $Page->firstRow . ',' . $Page->listRows;
		$this->count_view = $count_view;
		return $Page;
	}

	/******设置分页***/
	public function show_page($pager) {
		$this->pager = $pager;
		$this->page = $pager['show'];
		$totalPages = $this->pager['totalPages'];
		$this->totalPages = $totalPages;
		$parameter = $_GET;
		$parameter['p'] = I('p', 1, 'intval') + 1;
		if (!($totalPages < $parameter['p'])) {
			$this->nextUrl = U(ACTION_NAME, $parameter);
		} else {
			$this->nextUrl = "";
		}
		$GLOBALS['nextUrl'] = $this->nextUrl;
	}

	/******设置分页***/
	public function show_api_page($pager) {
		$this->pager = $pager;
		$this->page = $pager['show'];
		$totalPages = $this->pager['totalPages'];
		$this->totalPages = $totalPages;
		$parameter = $_GET;
		$parameter['p'] = I('p', 1, 'intval') + 1;
		if (!($totalPages < $parameter['p'])) {
			$this->nextUrl = api_url(API_NAME . "/" . API_CLASS . "/" . API_METHOD, $parameter);
		} else {
			$this->nextUrl = "";
		}
		$GLOBALS['nextUrl'] = $this->nextUrl;
	}

	/***display**/
	public function admin_display($content) {
		$tpl = $tpl ? $tpl : (CONTROLLER_NAME . "/" . ACTION_NAME);
		//dump($tpl);
		$this->adminMenu = C("ADMIN_VIEW_PATH") . "Public/adminMenu.html";
		$this->MemuList = $this->getIndexIco();
		$this->show_content = $content;
		if (IS_AJAX || I('IS_AJAX')) {
			echo $this->show_content;
		} else {
			$tpl = C("ADMIN_VIEW_PATH") . "Index/home.html";
			self::display($tpl);
		}
	}

	/*****权限图标***/
	protected function getIndexIco() {
		if (session('isSuper')) {
			$data = BoxModel("addon_auth_group")->where("is_show=1")->order("order_by")->select();
		} else {
			$data = BoxModel('addon_auth_group_user')->alias("U")->join("addon_auth_group as G on G.id=U.group_id")->order("U.order_by")->where(array('admin_id' => session('admin_id'), 'status' => 1, 'G.is_show=1'))->select();
		}
		//dump($data);
		/***********************当前选中的权限******************/
		if (!$group_id) {
			$group_id = I('auth_group_id');
		}
		$cur_group = I('auth_group_id'); //当前的权限group
		$memu = array(); //菜单
		if ($auth_id = I('auth_id')) {
			$where = "id='$auth_id' ";
		} else {
			$authcode1 = BOX_MODULE_NAME . "/" . CONTROLLER_NAME . "/" . ACTION_NAME; //box
			$authcode2 = MODULE_NAME . "/" . CONTROLLER_NAME . "/" . ACTION_NAME; //
			$authcode3 = "Addon/" . ADDON_NAME . "/" . ADDON_CLASS . "/" . ADDON_METHOD; //插件权限控制
			$where = "authcode in ('$authcode1','$authcode2','$authcode3') and group_id>0 ";
		}
		$auth_data = M("addon_auth")->order("id desc")->where($where)->find();
		$memuNav = $auth_data['short_name'] ? $auth_data['short_name'] : $auth_data['authcode'];
		$memuNav = I('memuNav', $memuNav);
		// dump($memuNav);
		if ($auth_data) {
			$cur_group = $auth_data['group_id'];
		}
		if ($group_id) {
			$map = "group_id='$group_id' and is_show=1";
		} else {
			$cur_group = $group_id = $auth_data['group_id'];
			$map = "group_id='" . $auth_data['group_id'] . "' and is_show=1";
		}
		if ($group_id) {
			$r = BoxModel("addon_auth_group")->where("id='$group_id'")->find();
			$this->cur_auth_group_cate = $r['cate'];
		}
		if (!$this->cur_auth_group_cate) {
			$this->cur_auth_group_cate = "signal";
		}
		$this->cur_auth_id = $auth_data['id']; //当前选中的
		$this->cur_group_id = $group_id; //当前选中的
		$this->cur_memuNav = $memuNav;
		/***********************当选中的权限*****************/
		foreach ($data as $k => $one) {
			if ($one['url']) {
				$data[$k]['url'] = $this->fetch("", $one['url']);
				$data[$k]['url'] .= "?auth_group_id=" . $one['id'];
			}
			//dump(array('auth_group_id'=>$one['id']));exit();
			$param = array('auth_group_id' => $one['id']);
			$data[$k]['submemu'] = hook("Auth/Index/getMemu", $param);
		}
		return $data;
	}

	public function _empty() {

	}

	protected function fetchHtml($data, $tpl, $variable) {
		if ($tpl) {
			//dump($data);
			$this->$variable = $data;
			return $this->fetch("", $tpl);
		}
	}

	/****生成jsController**/
	public function jsController() {
		$apps = getApps();
		$js_path = BOX_PATH . "/Public/";
		$jsControllerList = array();
		foreach ($apps as $app) {
			$path = $js_path . "Controllers/" . $app;
			if (is_dir($path)) {
				$controllers = getFile($path);
				foreach ($controllers as $one) {
					$name = trim(basename($one), ".js");
					$jsControllerList[] = '"' . $app . "_" . $name . '"';
				}
			}
		}
		$controller_path = $js_path . "/Controllers/controllers.js";
		$jsControllerStr = implode(",", $jsControllerList);
		$code = 'var controllers_list= new Array();controllers_list=[' . $jsControllerStr . '];';
		//dump($controller_path);
		//dump($code);exit();
		$bool = saveFile($controller_path, $code);
		//echo($jsControllerStr);
	}

	/*******合并js,和css***/
	public function resCache($tpls, $app = "BoxEdu") {
		if (is_file($tpls)) {
			$content = file_get_contents($tpls);
			$content = str_replace("__PUBLIC__", PUBLIC_PATH, $content);
			$pat = '/<script(.*?)src="(.*?)"(.*?)>(.*?)<\/script>/i';
			preg_match_all($pat, $content, $m);
			$pat = '/<link(.*?) resCache=1 href="(.*?)"(.*?)>/i';
			preg_match_all($pat, $content, $m2);
			//dump($m);

			/*****保存css js****/
			foreach ($m['2'] as $one) {
				$str1 .= file_get_contents(BOX_PATH . $one);
			}
//js
			foreach ($m2['2'] as $one) {
				$str2 .= file_get_contents(BOX_PATH . $one);
			}
//css
			// $name=time().great_rand(30);
			$name = $app;
			$res_cache_path = BOX_PATH . PUBLIC_PATH . "/res_cache";
			$this->save_res($res_cache_path . "/" . $name . ".css", $str2);

		}

	}

	public function save_res($path, $str) {
		$str = str_replace("\t", "", $str); //清除空格
		$str = str_replace("\r\n", "", $str);
		$str = str_replace("\n", "", $str);
		// 删除单行注释
		$str = preg_replace("/\/\/\s*[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/", "", $str);
		// 删除多行注释
		$str = preg_replace("/\/\*[^\/]*\*\//s", "", $str);
		saveFile($path, $str);
	}

}
